package com.usian.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.entity.ResultResponse;
import com.usian.feign.GoodsFeignService;
import com.usian.feign.UserFeignService;
import com.usian.mapper.OrderMapper;
import com.usian.model.record.Recordd;
import com.usian.service.IOrderService;

import com.usian.model.address.Address;
import com.usian.model.goods.Goods;
import com.usian.model.orders.Orders;
import com.usian.vo.GoodsVo;
import com.usian.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-12-17
 */
@Service
@Slf4j
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private GoodsFeignService goodsFeignService;




    @Override
    public List<Orders> findAll() {
        List<Orders> list = orderMapper.selectList(null);
        list.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));//倒序
        return list;
    }

    @Override
    public ResultResponse orderAdd(Integer id, Goods goods, Address address, Integer number) {
        log.info("订单数据：" + id + ", " + goods + ", " + address);
        //首先远程调用user用户服务，判断用户余额是否足够--
        Integer scoreId = userFeignService.findScoreId(id);
        System.out.println("账户总余额" + scoreId);
        if (scoreId < goods.getScore()* number) {
            return ResultResponse.error().message("账户积分余额不足");
        } else {
            //如果余额足够，扣减用户余额
            Integer updateScore = scoreId - (goods.getScore() * number);
            System.out.println("消费后的余额为：" + updateScore);
            UserVo userVo = new UserVo();
            userVo.setId(id);
            userVo.setScore(updateScore);
            userFeignService.updateScore(userVo);
        }
        //生成订单------
        Orders orders = new Orders();
        orders.setUserId(id); //下单的用户id
        orders.setGoodsId(goods.getGoodsId()); //商品编号
        orders.setName(goods.getName());  //商品名称
        orders.setPrice(goods.getPrice()); //商品价格
        orders.setAddressName(address.getName()); //收货人
        orders.setTel(address.getTel()); //收货人手机号
        orders.setProvince(address.getProvince()); //省份
        orders.setCity(address.getCity()); //城市
        orders.setCounty(address.getCounty()); //区县
        orders.setAddressDetail(address.getAddressDetail()); //详细地址
        orders.setImage(goods.getImage()); //商品图片
        orders.setStatus(2); //订单状态
        orders.setPayTime(new Date()); //支付时间
        orders.setCreateTime(new Date()); //创建时间
        orders.setScore(goods.getScore());//积分
        //随机生成订单号 -----------
        orders.setOrderId(String.valueOf(System.currentTimeMillis()));//订单号
        orders.setZong(goods.getScore() * number);
        orders.setPayScore(goods.getScore() * number);
        orders.setNumber(number);
        //远程调用修改商品兑换量接口   根据传递过来的商品编号查找商品，并将商品的兑换数量+ 购买量  ------------------------
        GoodsVo goodsVo = new GoodsVo();
        goodsVo.setNumbers(number);
        goodsVo.setId(goods.getGoodsId());
        goodsFeignService.findScoreId(goodsVo);
        //积分记录生成  ----------
        Recordd recordd = new Recordd();
        recordd.setName(goods.getName());
        recordd.setScore(goods.getScore()* number);
        recordd.setDatee(new Date());
        recordd.setUid(id);
        userFeignService.addRecord(recordd);
        log.info("订单数据：" + recordd);
        orderMapper.insert(orders);//插入订单数据
        return ResultResponse.ok().data("orders", orders).message("支付完成订单生成成功！");
    }

    @Override
    public ResultResponse orderAddGuan(Integer id, Goods goods, Address address, Integer number) {
        log.info("订单数据：" + id + ", " + goods + ", " + address);
        Orders orders = new Orders();
        orders.setUserId(id); //下单的用户id
        orders.setGoodsId(goods.getGoodsId()); //商品编号
        orders.setName(goods.getName());  //商品名称
        orders.setPrice(goods.getPrice()); //商品价格
        orders.setAddressName(address.getName()); //收货人
        orders.setTel(address.getTel()); //收货人手机号
        orders.setProvince(address.getProvince()); //省份
        orders.setCity(address.getCity()); //城市
        orders.setCounty(address.getCounty()); //区县
        orders.setAddressDetail(address.getAddressDetail()); //详细地址
        orders.setImage(goods.getImage()); //商品图片
        orders.setStatus(1); //订单状态
//        orders.setPayTime(new Date()); //支付时间
        orders.setCreateTime(new Date()); //创建时间
        orders.setScore(goods.getScore());//单价积分
        orders.setNumber(number); //购买数量
        orders.setZong(goods.getScore() * number); //单价X数量 = 总积分
        //随机生成订单号
        orders.setOrderId(String.valueOf(System.currentTimeMillis()));//订单号
        orderMapper.insert(orders);//插入订单数据
        return ResultResponse.ok().message("未支付订单生成成功！");
    }

    @Override
    public ResultResponse findOrdersByOrderId(String findId) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", findId);
        Orders orders = orderMapper.selectOne(queryWrapper);
        return ResultResponse.ok().data("orders", orders);
    }

    @Override
    public ResultResponse orderAdd02(Orders orders) {
        //远程调用user用户服务，查询用户余额是否足够
        Integer scoreId = userFeignService.findScoreId(orders.getUserId());
        if (scoreId < orders.getZong()) {
            return ResultResponse.error().message("账户积分余额不足");
        } else {
            //如果余额足够，扣减用户余额，生成订单，返回订单号
            Integer updateScore = scoreId - orders.getZong();
            System.out.println("消费后的余额为：" + updateScore);
            UserVo userVo = new UserVo();
            userVo.setId(orders.getUserId());
            userVo.setScore(updateScore);
            userFeignService.updateScore(userVo);
        }
        //远程调用修改商品兑换量接口   根据传递过来的商品编号查找商品，并将商品的兑换数量+1  ------------------------
        GoodsVo goodsVo = new GoodsVo();
        goodsVo.setNumbers(orders.getNumber());
        goodsVo.setId(orders.getGoodsId());
        goodsFeignService.findScoreId(goodsVo);
        //如果传递过来的订单号存在
        if (orderMapper.selectById(orders.getId()) != null) {
            orders.setStatus(2);
            orders.setPayTime(new Date()); //支付时间
            orders.setPayScore(orders.getZong()); //真正支付的积分
            //积分记录生成
            Recordd recordd = new Recordd();
            recordd.setName(orders.getName());
            recordd.setScore(orders.getPayScore());
            recordd.setDatee(new Date());
            recordd.setUid(orders.getUserId());
            userFeignService.addRecord(recordd);
            log.info("订单数据：" + recordd);
            orderMapper.updateById(orders);
            return ResultResponse.ok().data("orders", orders).message("支付完成订单生成成功！");
        } else {
            return ResultResponse.error().message("订单不存在");
        }
    }

    @Override
    public Orders findById(Integer id) {
        return orderMapper.selectById(id);
    }

    @Override
    public ResultResponse removeOrder(String findId) {
        QueryWrapper<Orders> qw = new QueryWrapper<>();
        qw.eq("order_id", findId);
        //根据传过来的订单编号修改订单状态
        Orders orders = new Orders();
        orders.setStatus(5);
        orderMapper.update(orders, qw);//修改订单状态
        return ResultResponse.ok().message("取消订单成功");
    }

    @Override
    public ResultResponse confirmReceipt(String findId) {
        QueryWrapper<Orders> qw = new QueryWrapper<>();
        qw.eq("order_id", findId);
        Orders orders = new Orders();
        orders.setStatus(4);
        orders.setOffTime(new Date());
        orderMapper.update(orders, qw);
        return ResultResponse.ok().message("确认收货成功");
    }

    @Override
    public Object status(Integer id) {
        Orders orders = orderMapper.selectById(id);
        orders.setSendTime(new Date());
        orders.setStatus(3);
        return orderMapper.updateById(orders);
    }

}
